package com.jiuyou.storeController.store;

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.collect.service.ICollectService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.StoreUserTokenService;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.order.service.IStoreProductOrderService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.store.service.IStoreService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.visitRecord.service.IVisitRecordService;
import com.ruoyi.wechat.util.CommonUtil;
import com.ruoyi.wechat.util.ConstantWeChat;
import com.ruoyi.wechat.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author chengliang
 * @date 2021/11/17
 **/
@RestController
@RequestMapping("/store/storeB")
@Api(tags = {"门店控制器"})
public class StoreStoreController extends StoreBaseController {

    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private StoreUserTokenService tokenService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IStoreProductOrderService orderService;
    @Autowired
    private ICollectService collectService;
    @Autowired
    private IVisitRecordService recordService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 获取 佣金二维码图片
     * @return
     */
    public String storeCommission(Long storeId){
        if(null==storeId){
            StoreUserRole storeUserRole=getStoreUserRole();
            storeId= storeUserRole.getStoreId();
        }
        System.out.println("tangyin");
        System.out.println(storeId);
        Store store=storeService.selectStoreById(storeId);
        String commissionImageUrl=store.getCommissionImageUrl();
        if(!StringUtils.isEmpty(commissionImageUrl)){
            return commissionImageUrl;
        }
        String APPKEY="YQS_C";
        String requrl= serverConfig.getUrl();
        JSONObject param=new JSONObject();
        String qrcodePage="";
        String scene="";
        String page="";
        //图书，进入章节目录
        scene="bindId="+storeId;
        page="pages/mall/home/home";
        param.put("scene",scene);
        param.put("page",page);
        qrcodePage=page+"?"+scene;
        String pro_env=sysConfigService.selectConfigByKey(DicConstants.PRO_ENV.getCode());
        if(null==pro_env){
            return null;
        }
        if(DicConstants.SYS_Y.getCode().equals(pro_env)){
            //正式环境
            param.put("env_version","release");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        }else{
            //测试参数，体验版使用，不要在正式使用
            param.put("env_version","trial");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            param.put("check_path",false);
        }
        String codeName=storeId+"_commission_"+ IdUtils.fastUUID();
        String xml = JSONObject.toJSONString(param);
        String requestUrl= ConstantWeChat.GET_WX_ACODE_UNLIMIT.replace("#ACCESS_TOKEN#", tokenUtil.getToken(APPKEY).getAccessToken());
        JSONObject resultR= commonUtil.doPostFile(requestUrl,xml,codeName,requrl);
        if(resultR.containsKey("imgUrl")){
            String imgUrl=resultR.getString("imgUrl");
            String fileAbsolutePath=resultR.getString("fileAbsolutePath");

            Store storeUpdate=new Store();
            storeUpdate.setId(storeId);
            storeUpdate.setCommissionImageLocal(fileAbsolutePath);
            storeUpdate.setCommissionImageUrl(imgUrl);
            storeUpdate.setCommissionPage(qrcodePage);
            storeService.updateStore(storeUpdate);
            return imgUrl;
        }
        return null;
    }

    /**
     * 获取 绑定为下级二维码图片
     * @return
     */
    public String storeBelow(Long storeId){
        if(null==storeId){
            StoreUserRole storeUserRole=getStoreUserRole();
            storeId= storeUserRole.getStoreId();
        }
        System.out.println("tangyin2");
        System.out.println(storeId);
        Store store=storeService.selectStoreById(storeId);
        String belowImageUrl=store.getBelowImageUrl();
        if(!StringUtils.isEmpty(belowImageUrl)){
            return belowImageUrl;
        }
        long userId = getLoginStoreUserId();
        String APPKEY="YQS_C";
        String requrl= serverConfig.getUrl();
        JSONObject param=new JSONObject();
        String qrcodePage="";
        String scene="";
        String page="";
        //图书，进入章节目录
        scene="bindId="+storeId+"&userId="+userId;
        page="pages/UCenter/index/index";
        param.put("scene",scene);
        param.put("page",page);
        qrcodePage=page+"?"+scene;
        String pro_env=sysConfigService.selectConfigByKey(DicConstants.PRO_ENV.getCode());
        if(null==pro_env){
            return null;
        }
//        param.put("env_version","develop");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
//        param.put("check_path",false);
        //System.out.println(pro_env);
        if(DicConstants.SYS_Y.getCode().equals(pro_env)){
            System.out.println("正式");
            //正式环境
            param.put("env_version","release");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        }else{
            System.out.println("体验");
            //测试参数，体验版使用，不要在正式使用
            param.put("env_version","trial");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            param.put("check_path",false);
        }
        String codeName=storeId+"_commission_"+ IdUtils.fastUUID();
        String xml = JSONObject.toJSONString(param);
        String requestUrl= ConstantWeChat.GET_WX_ACODE_UNLIMIT.replace("#ACCESS_TOKEN#", tokenUtil.getToken(APPKEY).getAccessToken());
        JSONObject resultR= commonUtil.doPostFile(requestUrl,xml,codeName,requrl);
        if(resultR.containsKey("imgUrl")){
            String imgUrl=resultR.getString("imgUrl");
            String fileAbsolutePath=resultR.getString("fileAbsolutePath");

            Store storeUpdate=new Store();
            storeUpdate.setId(storeId);
            storeUpdate.setBelowImageLocal(fileAbsolutePath);
            storeUpdate.setBelowImageUrl(imgUrl);
            storeUpdate.setBelowPage(qrcodePage);
            storeService.updateStore(storeUpdate);
            return imgUrl;
        }
        return null;
    }


    /**
     * 此方法不要再调用，适配审核阶段的老版本小程序，小程序审核后可删除
     * @return
     */
    @GetMapping
    @ApiOperation("获取门店详情")
    public Store getStoreDetail(){

        StoreUserRole storeUserRole = getStoreUserRole();
        if(null == storeUserRole){
            return null;
        }
        return storeService.selectStoreById(storeUserRole.getStoreId());
    }

    /**
     * 新的获取门店详情，方便管理和选择不同的门店
     * @param storeId
     * @return
     */
    @PostMapping("/getStore")
    @ApiOperation("获取门店详情")
    public Store getStoreDetail(Long storeId){
//        getStoreUser()
        StoreUserRole storeUserRole = getStoreUserRole(storeId);
        if(null == storeUserRole){
            return null;
        }
        storeCommission(storeId);//推广二维码
        storeBelow(storeId);//绑定为下级二维码
        return storeService.selectStoreById(storeUserRole.getStoreId());
    }

    /**
     * 获取当前所有权限汇总
     * @return
     */
    @PostMapping("/getRoleTypes")
    @ApiOperation("获取当前所有权限汇总")
    public AjaxResult getRoleTypes(){


        return AjaxResult.success( getStoreUserRoleTypes());
    }


    /**
     * 获取我有权限的门店列表
     * @return
     */
    @PostMapping("/getMyStoreList")
    public AjaxResult getMyStoreList(){

        Long storeUserId= getLoginStoreUserId();
        List<Store> list=storeService.selectStoreByUserId(storeUserId);
        return AjaxResult.success(list);
    }

    /**
     *检测提醒
     * @return
     */
    @PostMapping("/checkTips")
    public AjaxResult checkTips(){
        JSONObject jso=new JSONObject();
        StoreUserRole storeUserRole = getStoreUserRole();
        if(null == storeUserRole){
            return AjaxResult.error();
        }
        Long storeId=storeUserRole.getStoreId();
        Store store=storeService.selectStoreById(storeId);
        Date vipTime=store.getVipTime();
        String vipState= store.getVipState();
        if(DicConstants.SYS_Y.getCode().equals(vipState)){
            //有效期内
            Date date30=DateUtils.addDays(new Date(),30);
            if(null!=vipTime&&date30.compareTo(vipTime)>0){
                //到期不足30天
                //需要提醒
                jso.put("tips","Y");
                jso.put("tipsMsg","您的会员即将到期。");
            }

        }
        return AjaxResult.success(jso);
    }
    @PostMapping("/getData")
    public JSONObject getStoreYesterdayData(){
        JSONObject j = new JSONObject();
        j.put("success",false);
        j.put("msg","失败");
        try {

            StoreUserRole storeUserRole = getStoreUserRole();
            StoreProductOrder order = new StoreProductOrder();
            Long storeId=storeUserRole.getStoreId();
//            order.setVerifyCodeTime();
            order.getParams().put("verifyCodeTimYMDStr",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,DateUtils.getYesterday()));
            order.setStoreId(storeId);
            //order.setPayState(DicConstants.SYS_Y.getCode());
            order.setOrderState(DicConstants.ORDER_STATE_Used.getCode());

            List<StoreProductOrder> storeProductOrders = orderService.selectStoreProductOrderList(order);
            BigDecimal totalPrice = BigDecimal.ZERO;
            int totalSales = 0;
            for (Iterator iter  = storeProductOrders.iterator(); iter.hasNext();)
            {
                StoreProductOrder o = (StoreProductOrder) iter.next();
                totalPrice = totalPrice.add(o.getTotalPrice());
                totalSales += 1;
            }
            Integer num = recordService.selectYesterdayNum(storeUserRole.getStoreId());
            j.put("success",true);
            j.put("msg","成功");
            j.put("totalSales", totalSales);
            j.put("totalPrice",totalPrice);
            j.put("visitNum",num);
            return j;
        }catch (Exception e){
            logger.error(e.getMessage());
            return j;
        }


    }

    public static void main(String[] args) {
        Calendar cal  =   Calendar.getInstance();
        cal.add(Calendar.DATE,  -1);
        System.out.println(cal.getTime());
        Date date = DateUtils.dateTime("yyyy-MM-dd", cal.getTime().toString());
//        System.out.println(date);
    }

}
